package com.katesoft.scale4j.rttp.jobs;

import org.quartz.JobDataMap;
import org.springframework.batch.core.Job;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.scheduling.quartz.JobDetailBean;

import static com.katesoft.scale4j.common.services.IBeanNameReferences.RTTP_BATCH_JOB_LAUNCHER;
import static com.katesoft.scale4j.common.services.IBeanNameReferences.RTTP_BATCH_JOB_REGISTRY;
import static com.katesoft.scale4j.rttp.jobs.JobsUtility.JOB_NAME;
import static com.katesoft.scale4j.rttp.jobs.SpringBatchJobLauncher.JOB_LAUNCHER;
import static com.katesoft.scale4j.rttp.jobs.SpringBatchJobLauncher.JOB_LOCATOR;

/**
 * This class will add jobLauncher and jobRegistry references to jobDataMap.
 * <p/>
 * Then we will use those references to retrieve actual beans and launch spring batch job execution.
 * 
 * @author kate2007
 */
public class RttpJobDetailBean extends JobDetailBean {
   private static final long serialVersionUID = -7068116314132048836L;
   private Job job;

   @Override
   public void afterPropertiesSet() {
      if (!getJobDataMap().containsKey(JOB_NAME)) {
         if (job == null) {
            throw new BeanCreationException(
                     String.format(
                              "jobName is not specified, this is mandatory property. You can set-up jobNam using jobDataAsMap with key='%s'",
                              JOB_NAME));
         }
         getJobDataMap().put(JOB_NAME, job.getName());
      }
      //
      String jobName = getJobDataMap().getString(JOB_NAME);
      if (getName() == null) {
         setName("rttp.quartz." + jobName);
      }
      //
      JobDataMap jobDataMap = getJobDataMap();
      if (!jobDataMap.containsKey(JOB_LAUNCHER)) {
         jobDataMap.put(JOB_LAUNCHER, RTTP_BATCH_JOB_LAUNCHER);
      }
      if (!jobDataMap.containsKey(JOB_LOCATOR)) {
         jobDataMap.put(JOB_LOCATOR, RTTP_BATCH_JOB_REGISTRY);
      }
      //
      super.afterPropertiesSet();
   }

   @Required
   public void setJob(Job job) {
      this.job = job;
   }

   public Job getJob() {
      return job;
   }
}
